import type { Meta, StoryObj } from '@storybook/vue3';
import CrudForm from '@/components/crud/form/CrudForm.vue';
import type { FormConfig } from '@/components/crud/types';
import {openCreateDialog} from "@/components/crud/form/FormDialog";
import {getCurrentInstance} from "vue";

// 定义表单配置
const formConfig: FormConfig[] = [
    {
        title: '姓名',
        field: 'name',
        rules: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        component: {
            name: 'el-input',
            width: 100,
            attrs: {
                placeholder: '请输入姓名',
            },
        },
    },
    {
        title: '邮箱',
        field: 'email',
        rules: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
        ],
        component: {
            name: 'el-input',
            width: 200,
            attrs: {
                placeholder: '请输入邮箱',
            },
        },
    },
];

// 定义元数据
const meta: Meta<typeof CrudForm> = {
    title: 'CRUD/Form',
    component: CrudForm,
    tags: ['autodocs'],
    argTypes: {
        config: {
            control: 'object',
            description: '表单配置',
        },
        modelValue: {
            control: 'object',
            description: '表单数据，用于双向绑定',
        },
        initialData: {
            control: 'object',
            description: '表单初始数据',
        },
        onSubmit: {
            action: 'submit',
            description: '表单提交事件',
        },
        onCancel: {
            action: 'cancel',
            description: '表单取消事件',
        },
    },
};

export default meta;
type Story = StoryObj<typeof CrudForm>;

// 基础使用示例
export const BasicUsage: Story = {
    render: (args) => ({
        components: { CrudForm },
        setup() {
            return { args };
        },
        template: `
      <CrudForm
        v-bind="args"
        @submit="args.onSubmit"
        @cancel="args.onCancel"
        @update:modelValue="args['update:modelValue']"
      />
    `,
    }),
    args: {
        config: formConfig,
        modelValue: {
            name: '',
            email: '',
        },
        initialData: {
            name: '',
            email: '',
        },
    },
};

// 带初始数据的示例
export const Dialog: Story = {
    render: (args) => ({
        components: { CrudForm },
        setup() {
            function open () {
                openCreateDialog(getCurrentInstance(),'tests', '添加用户', formConfig, () => {
                    console.log('创建成功');
                })

            }
            return { args , open};
        },
        template: `
         <el-button @click="open" type="primary">打开创建弹窗</el-button>
    `,
    }),
};
